const query = require('./pool')
//用于生成和解析token
let jwt = require('jsonwebtoken');
let signkey = 'lin_da_da_yo';
/**
 *  保存帐号
 */
 exports.save = function (user) {
  user.password = user.password
  return new Promise((resolve,reject)=>{
    const [err, data] = query(`INSERT INTO user (id,password) value ('${user.id}','${user.password}')`)
    if (err) {
      reject(err)
    } else {
      resolve(data)
    }
  })
}

/**
 *  查找一个帐号
 */
exports.findOne = async function (user) {
  [err, data] = await query(`SELECT * FROM user WHERE username = '${user.username}'`)
  if (err) {
    throw new Error(err)
  } else {
    return data
  }
}
// 生成token
exports.setToken = function(username,password){
  return new Promise((resolve,reject)=>{
    const token = jwt.sign({
      name: username,
      password: password
    },signkey,{ expiresIn:'24h' });
    resolve(token);
  })
}
// 验证token
exports.verToken = function(token){
  return new Promise((resolve,reject)=>{
    const info = jwt.verify(token.split(' ')[1],signkey);
    resolve(info);
  })
}

exports.to = function(promise, errorProps = {}, errorFirst = true) {
	return promise.then((data) => {
    return errorFirst ? [null, data] : [data, null]
  })
    .catch(err => {
      if(errorProps) Object.assign(err, errorProps)
      errorFirst ? [err, undefined] : [undefined, err]
    })
  }
